from flask import Blueprint, jsonify, make_response, redirect
from flask_restful import request
from application.models.users.user import *
from application.tools.myredis import r
from application.tools.captcha.captcha import captcha
from application.tools.sendmsg import senMsg
from application.tools.myjwt import mjwt
import random, time, functools, json,datetime
from app import db

user_blue = Blueprint("userblue",__name__)

# # 装饰器
# def decorator1(func):
#     def wrapper1(*args, **kwargs):
#         print(func.__name__)
#         print("这是第一个装饰器, 执行时间为: ", datetime.datetime.now())
#         time.sleep(5)
#         return func(*args, **kwargs)
#     return wrapper1
#
# # 测试
# @decorator1
# @user_blue.route("/test")
# def test():
#     print("执行test")
#     return jsonify({"code": 200, "msg":"msg"})

# 装饰器
# def islogin(type):
#     def pemistion(func):
#         @functools.wraps(func)
#         def wrapper():
#             func()
#             if type ==1:
#                 return redirect("http://www.baidu.com")
#             else:
#                 return redirect("http://www.jd.com")
#         return wrapper
#     return pemistion
#
# @user_blue.route("/test")
# @islogin(2)
# def test():
#     print("执行test")
#     return jsonify({"code":200,'msg':'msg'})


# 无参装饰器
# def islogin(func):
# 	@functools.wraps(func)
# 	def wrapper():
# 		return func()
# 	return wrapper
#
#
# #测试
# @user_blue.route("/test")
# @islogin
# def test():
#     print("执行test")
#     return jsonify({"code":200,'msg':'msg'})


# 多个装饰器的顺序
# def decorator1(func):
#     def wrapper1(*args, **kwargs):
#         print(func.__name__)
#         print("这是第一个装饰器, 执行时间为: ", datetime.datetime.now())
#         time.sleep(5)
#         return func(*args, **kwargs)
#     return wrapper1
#
# def decorator2(func):
#     def wrapper2(*args, **kwargs):
#         print(func.__name__)
#         print("这是第二个装饰器, 执行时间为: ", datetime.datetime.now())
#         time.sleep(5)
#         return func(*args, **kwargs)
#     return wrapper2
#
# @decorator1  # 此处即 func5 = decorator1(decorator2(func5))
# @decorator2  # 此处即 func5 = decorator2(func5)
# def func5():
#     print("这是原函数，执行时间为: ", datetime.datetime.now())
#
# func5()


# 获取图片验证码
@user_blue.route("/getcode")
def getcode():
    #生成图片验证码 text文字  image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid作为redis key
    # data = request.json
    # uuid = data["uuid"]
    uuid = str(request.args.get("uuid"))
    print(text)

    # 存入redis
    r.str_add(uuid, text, 60)


    # 以流的方式生成验证码
    res = make_response(image)
    res.headers["Content-Type"] = "image/jpg"

    return res



# 发送短信验证码
@user_blue.route("/sendSmsCode", methods=["POST"])
def send():
    data = request.json
    if data:
        # 获取参数
        uuid = data["uuid"]
        piccode = data["piccode"]
        mobile = data["mobile"]
        print(uuid)
        # 通过uuid查询验证码
        value = r.str_get(uuid)
        print(value)

        if value:
            # 两个图形验证码对比， 如果成功调用短信平台发送短信
            if piccode.lower() == value.lower():
                # 一分钟只能发一次
                value = r.str_get(mobile)
                if value:
                    return jsonify({'code':10012, "msg": "一分钟内不能重发"})
                code = str(random.randint(100000, 999999))
                print(code)
                # 调用短信平台
                flag = senMsg(mobile, code)
                # 判断是否发送成功
                print(flag)
                if flag == True:
                    # 短信验证码存入redis
                    r.str_add(mobile, code, 60)
                    # 删除图形验证码
                    r.del_str(uuid)
                    # 返回结果
                    return jsonify({'code':200,"msg":"发送成功"})
                # 调用失败返回结果
                else:
                    return jsonify({"code":10013,"msg":"发送短信验证码失败"})
            # 图片验证码错误
            else:
                return jsonify({"code":10011, "msg": "图片验证码错误"})
        else:
            return jsonify({"code": 10012, "msg": "验证码错误"})
    else:
        return jsonify({"code":400,"msg":"参数不全"})

# 登录注册
@user_blue.route("/login", methods=["POST"])
def login():
    data = request.json
    if data:
        # 获取参数, 手机号， 验证码
        code = request.json.get("code")
        mobile = request.json.get("mobile")
        # 获取手机验证码
        code = r.str_get(mobile)
        if code:
            # 判断验证码是否相同
            if int(code) == int(code):
                # 如果相同查询数据库user表
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    # 删除redis中的验证码
                    pass
                    # r.del_str(mobile)
                else:
                    # 注册添加数据
                    u = User(mobile=mobile, nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    # 获取数据返回用户id
                    user = User.query.filter(User.mobile == mobile).first()
                # 用用户信息生成jwt token
                # token = Myjwt.jwt_encode(data={"data":{"uid":user.id,"exp":int(time.time())}})
                token = mjwt.jwt_encode(data={"data":{"uid":user.id,"exp":int(time.time())}})
                print(token)
                return jsonify({"code":200,"token": token,"userid":user.id})
                # 返回页面
            else:
                return jsonify({'code':10021,"msg":"验证码错误"})
        else:
            return jsonify({'code': 10022, "msg": "验证码过期"})
    else:
        return jsonify({"code":400,"msg":"数据不全"})






















